package com.itheima.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.List;

/**
 * @author wuzhiyong
 */
@Component
@Configuration
public class AliyunOssUtil {

    @Value("oss-cn-guangzhou.aliyuncs.com")
    private String endpoint;

    @Value("LTAI5t9waFds9V7vuvJPbBQY")
    private String accessKeyId;

    @Value("beXZVsTgJ56ptUsTBiWUBHM3AL3c8s")
    private String accessKeySecret;

    @Value("reggieoss")
    private String bucketName;

    private OSS ossClient;

    /**
     * 初始化oss实例
     * 单例
     *
     * @return ossClient
     */
    private OSS getInstance() {
        //控制并发
        if (ossClient == null) {
            synchronized (AliyunOssUtil.class) {
                if (ossClient == null) {
                    ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
                }
            }
        }
        return ossClient;
    }

    /**
     * 上传
     */
    public void upload(InputStream file, String fileName) {
        getInstance().putObject(bucketName, fileName, file);
    }

    /**
     * 删除文件
     */
    public void deleteFile(String fileName) {
        OSS ossClient = getInstance();
        try {
            ossClient.deleteObject(bucketName, fileName);
        } catch (final Exception e) {
            System.out.println("删除文件失败, 文件名称 -> " + fileName);
        } finally {
            //保证能释放掉
            ossClient.shutdown();
        }
    }

    /**
     * 查询文件图片列表
     */
    public List<OSSObjectSummary> list() {
        // 设置最大个数。
        final int maxKeys = 200;
        // 列举文件。
        ObjectListing objectListing = getInstance().listObjects(new ListObjectsRequest(bucketName).withMaxKeys(maxKeys));
        return objectListing.getObjectSummaries();
    }
}

